﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Web;

namespace ASPNETVN.PORTAL.Components.Helpers
{
    public class DownloadHelper
    {
        private static void copyStream(Stream FromStream, Stream ToStream)
        {
            const int intSize = 4096;
            Byte[] buffer = new Byte[intSize];
            int intBytesRead = FromStream.Read(buffer, 0, intSize);
            while (intBytesRead > 0)
            {
                ToStream.Write(buffer, 0, intBytesRead);
                intBytesRead = FromStream.Read(buffer, 0, intSize);
            }
        }

        public static void DownloadImage(string url, string pathToSave)
        {
            HttpContext context = HttpContext.Current;
            
            string physicalDirectory = context.Server.MapPath(pathToSave);            
            if (!Directory.Exists(physicalDirectory))
            {
                Directory.CreateDirectory(physicalDirectory);
            }

            string sourceFileName = url.Substring(url.LastIndexOf('/') + 1);
            string physicalPath = physicalDirectory + "\\" + sourceFileName;

            int i = 1;
            while (File.Exists(physicalPath))
            {
                physicalPath = physicalDirectory + "\\" + i + "_" + sourceFileName;
                i++;
            }

            // Bắt đầu download.
            MemoryStream ms = null;
            FileStream fs = null;

            WebRequest req = WebRequest.Create(url);
            req.Method = "GET";
            WebResponse rsp = null;

            try
            {
                rsp = req.GetResponse();
                ms = new MemoryStream();

                copyStream(rsp.GetResponseStream(), ms);
                fs = new FileStream(physicalPath, FileMode.Create);
                fs.Write(ms.ToArray(), 0, (int)ms.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (ms != null) ms.Close();
                if (rsp != null) rsp.GetResponseStream().Close();
                if (fs != null) fs.Close();
            }
            // Hoàn thành download.

            // Tạo thumbnail.
            string physicalThumbnailDirectory = physicalDirectory + "\\Thumbnails\\";
            if (!Directory.Exists(physicalThumbnailDirectory))
            {
                Directory.CreateDirectory(physicalThumbnailDirectory);
            }

            string physicalThumbnailPath = physicalThumbnailDirectory + "\\" + sourceFileName;
            i = 1;
            while (File.Exists(physicalThumbnailDirectory))
            {
                physicalThumbnailPath = physicalThumbnailDirectory + "\\" + i + "_" + sourceFileName;
                i++;
            }

            // Tạo thumbnail image.
            Image fullPicture;
            try
            {
                // Chỉnh kích thước thumbnail image từ image.
                fullPicture = new Bitmap(physicalPath);
                Image thumbnail = ImageHelper.ResizeImage(fullPicture, 120, 80, ImageResizeOption.MaintainAspectWidth);
                fullPicture.Dispose();

                // Chỉnh kích thước mới cho image.
                fullPicture = new Bitmap(physicalPath);
                Image original = ImageHelper.ResizeImage(fullPicture, 640, 480, ImageResizeOption.MaintainAspectWidth);
                fullPicture.Dispose();

                // Xóa image vừa upload, chỉ lấy image đã chỉnh kích cỡ.
                if (File.Exists(physicalPath))
                {
                    File.Delete(physicalPath);
                }

                string ext = sourceFileName.Substring(sourceFileName.LastIndexOf('.'));
                switch (ext.ToLower())
                {
                    case ".jpg":
                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Jpeg);
                        original.Save(physicalPath, ImageFormat.Jpeg);
                        break;
                    case ".png":
                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Png);
                        original.Save(physicalPath, ImageFormat.Png);
                        break;
                    case ".gif":
                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Gif);
                        original.Save(physicalPath, ImageFormat.Gif);
                        break;
                    case ".bmp":
                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Bmp);
                        original.Save(physicalPath, ImageFormat.Bmp);
                        break;
                }
                thumbnail.Dispose();
                original.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("Error in create thumbnail: " + ex.Message);
            }
        }
    }
}